'''
Created on 2020年3月3日

@author: Administrator
'''
from flask import json
import os
from common.public import *
from config import *
from peewee import JOIN
from orm.model import  User, Dept, Customer, MyCustomer, TransForm, db, SummaryTrack, TransFormDetail, ServiceDetail, TransFormRecorder,Service
from view.baseview import BaseView
from view.mycustomerview import MyCustomerView


class TransFormView(BaseView):
    def __init__(self):
        pass 

    def query(self, params):
        """  根据条件取得流转单列表，params：条件参数  """
        result=[]
        print(params)
        # 取得附件文件列表
        filelist = {}
        for entry in os.listdir(DOWNLOAD_PATH_TRANSFORM_ANNEX1):
            # 使用os.path.isfile判断该路径是否是文件类型
            if os.path.isfile(os.path.join(DOWNLOAD_PATH_TRANSFORM_ANNEX1, entry)):

                substrings = entry.split('.')
                if len(substrings)==2:
                    filelist[substrings[0]] = entry
                    print("正确：",  entry)
                else:
                    print("错误：", entry)
        where_condition = True
        if params["keyword"]:
            likestr= "%"+params["keyword"] +"%"
            where_condition=(Customer.compname ** likestr )
            where_condition=where_condition | (Customer.contacter** likestr )
            where_condition=where_condition | (Customer.area** likestr )
            where_condition=where_condition | (Customer.phone** likestr )

        # 取得部门管辖区域
        if params["userid"]:
            user = User.get(User.id == params["userid"])
            # 取得部门列表ID
            deptids = Dept.select(Dept.id).where(Dept.up_id==user.dept_id)
            if deptids:
                # 如果取到部门列表，说明是总经办部门人员
                pass
            else:
                # 如果取不到部门列表，说明是总经办部门以外人员
                leader = User.select().where(User.id==params["userid"]).first()
                ids = []
                if leader.isleader == COMMON_TRUE:
                    # 如果是主管
                    rows = User.select(User.id).where(User.leader_id==params["userid"])
                    for row in rows:
                        ids.append(row.id)
                    ids.append(params["userid"])
                else:
                    ids.append(params["userid"])
                where_condition=where_condition &(TransForm.seller.in_(ids) | TransForm.outformer.in_(ids) | 
                                                  TransForm.finance.in_(ids) | TransForm.handover.in_(ids) | 
                                                  TransForm.receiver.in_(ids) | TransForm.supervisor.in_(ids))
        if params["personnel"]:
            where_condition=where_condition &(TransForm.seller.in_(params["personnel"]) | TransForm.outformer.in_(params["personnel"]) | 
                                              TransForm.finance.in_(params["personnel"]) | TransForm.handover.in_(params["personnel"])  | 
                                              TransForm.receiver.in_(params["personnel"])| TransForm.supervisor.in_(params["personnel"]))

        if params["signtype"]:
            where_condition=where_condition &(TransForm.signtype.in_(params["signtype"]))
        if params["endedamount"]:
            if params["endedamount"] == COMMON_TRUE:
                where_condition = where_condition & (TransForm.amountend == 0)
            else:
                where_condition = where_condition & (TransForm.amountend != 0)
        if params["formtype"]:
            where_condition=where_condition &(TransForm.formtype.in_(params["formtype"]))
        if params["status"]:
            where_condition=where_condition &(TransForm.status.in_(params["status"]))
        if params["datetime"]:
            likestr= params["datetime"] 
            where_condition=where_condition & (((TransForm.transdate >= params["datetime"][0]) & (TransForm.transdate <= params["datetime"][1])) )
        total = TransForm.select().join(Customer, JOIN.LEFT_OUTER, on=(Customer.id == TransForm.customer_id)).where(where_condition).count()
        rows = TransForm.select().join(Customer, JOIN.LEFT_OUTER, on=(Customer.id == TransForm.customer_id)).where(where_condition).order_by(TransForm.transdate.desc(),TransForm.customer_id).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            service = []
            recorder =  []
            # 服务明细
            trows = TransFormDetail.select().where(TransFormDetail.transform == row.id)
            for trow in trows:
                try:
                    service.append({"id":trow.id, "transformid":trow.transform_id, "spec":trow.servicedetail.spec, "type":trow.servicedetail.type, "servicedetailid":trow.servicedetail_id, \
                                    "name":trow.service.name, "serviceid":trow.service_id, "items":trow.servicedetail.items, "amount":trow.amount, "totalprice":trow.totalprice, "unit":trow.unit, \
                                    "cost":trow.cost, "price":trow.price, "memo":trow.memo})
                except:
                    continue

            # 收款 记录
            rrows = TransFormRecorder.select().where(TransFormRecorder.transform == row.id)
            for rrow in rrows:
                annexs=[]
                userid = 0
                username = ''
                if rrow.reciver_id == 0:
                    userid = 0
                    username = ''
                else:
                    userid = rrow.reciver_id
                    username = rrow.reciver.username
                for annex in json.loads(rrow.annex):
                    annexs.append({"name":annex,"url":API_TRANSFORMRECORDER_ANNEX_DOWNLOAD +str(row.mycustomer_id) + "/" + annex})
                recorder.append({"id":rrow.id, "transformid":rrow.transform_id, "collectiondate":str(rrow.collectiondate), \
                                 "loantype":rrow.loantype, "totalprice":rrow.totalprice, "annex":annexs, \
                                 "reciverid":userid,"reciver":username,"memo":rrow.memo})
            newprice=0
            oldprice=0
            preferential_description=""
            if row.discount_id != 0:
                newprice=row.discount.new_price
                oldprice=row.discount.price
                preferential_description=row.discount.preferential_description
            #print(row.annex)
            sannex = []
            print("filelistXXXXXXXXXXXXXXXXX:",filelist)
            print("row:",row)
            #print("row.mycustomer:",row.mycustomer)
            myid = 0
            try:
                if str(row.mycustomer.id) in filelist:
                    sannex = [filelist[str(row.mycustomer.id)]]
                myid = row.mycustomer.id
            except IOError:
                print ('mycustomer not Exists')
            except:
                
                print ('process exception')


            data = {
                "id":row.id,
                "sellerid":row.seller.id,
                "sellername":row.seller.username,
                "outformerid":row.outformer.id,
                "outformername":row.outformer.username,
                "src":row.src,
                "signtype":row.signtype,
                "service":service,
                "recorder":recorder,
                "collectiondate":str(row.collectiondate),
                "transdate":str(row.transdate),
                "compname":row.customer.compname,
                "legalperson":row.customer.legalperson,
                "contacter":row.customer.contacter,
                "area":row.customer.area,
               "address":row.customer.address,
               "phone":row.customer.phone,
               "addresstype":row.addresstype,
               "business":row.business,
               "invoicingtype":row.invoicingtype,
               "amountinvoicing":row.amountinvoicing,
               "taxtype":row.customer.taxtype,
               "gifts":row.gifts,
               "amounttotal":row.amounttotal,
               "amountreceivables":row.amountreceivables,
               "amountpayin":row.amountpayin,
               "amountend":row.amountend,
               "paytype":row.paytype,
               "payimg":row.payimg,
               "amountendcondition":row.amountendcondition,
               "financeid":row.finance.id,
               "financename":row.finance.username,
               "financestatus":row.financestatus,
               "materials":json.loads(row.materials),
               "handoverid":row.handover.id,
               "handovername":row.handover.username,
               "handoverstatus":row.handoverstatus,
               "receiverid":row.receiver.id,
               "receivername":row.receiver.username,
               "receiverstatus":row.receiverstatus,
               "supervisorid":row.supervisor.id,
               "supervisorname":row.supervisor.username,
               "supervisorstatus":row.supervisorstatus,
               "mycustomerid":myid,
               "customerid":row.customer.id,
               "status":row.status,
               "formtype": row.formtype,
               "annex": sannex,
               "memo":row.memo,
               "discount_id":row.discount_id,
               "preferentialdescription":preferential_description,
               "newprice":newprice,
               "oldprice":oldprice

             }
            result.append(data)
        return super().resultSet(200, "", result, total=total)
    
    @db.atomic()                   
    def nopass(self, params):
        """
        驳回
        """
        message = ""
        transForm = TransForm.get(TransForm.id==params["id"])

        if params["formtype"] != TRANSFORM_TYPE_ENDED:
            # 如果是正常流转单
            # 修改我的客户状态为已签约
            mc = MyCustomer.get(MyCustomer.id == params["mycustomerid"])
            mc.status = MYCUSTOMER_STATUS_SIGNED
            mc.save()
        if int(params["userid"]) == params["supervisorid"]:
            # 主管驳回时
            transForm.supervisorstatus = AUDIT_STATUS_CANCLE
            transForm.status = AUDIT_STATUS_CANCLE
            if transForm.memo == "":
                transForm.memo = params["memo"]
            else:
                transForm.memo = transForm.memo + '\n' + params["memo"]
            transForm.save()

            return super().resultSet(200, "已驳回给市场专员重新流转。", [])
        elif int(params["userid"]) == params["financeid"]:
            # 财务 2
            if transForm.supervisorstatus==AUDIT_STATUS_PASSED:
                #如果主管已审核
                #transForm.supervisorstatus=AUDIT_STATUS_WAITE
                transForm.financestatus=AUDIT_STATUS_CANCLE
                transForm.status = AUDIT_STATUS_CANCLE
                if transForm.memo == "":
                    transForm.memo = params["memo"]
                else:
                    transForm.memo = transForm.memo + '\n' + params["memo"]
                transForm.save()
                message = "已驳回给主管重新审核。"
            else:
                #如果主管未审核
                return super().resultSet(201, "主管还未审核通过,您无法驳回。", [])
        elif int(params["userid"]) == params["receiverid"]:
            # 接收人4
            if transForm.financestatus==AUDIT_STATUS_PASSED:
                #如果账务已审核
                #transForm.supervisorstatus = AUDIT_STATUS_WAITE
                #transForm.financestatus=AUDIT_STATUS_CANCLE
                transForm.receiverstatus=AUDIT_STATUS_CANCLE
                transForm.status = AUDIT_STATUS_CANCLE
                if transForm.memo == "":
                    transForm.memo = params["memo"]
                else:
                    transForm.memo = transForm.memo + '\n' + params["memo"]
                transForm.save()
                message = "已驳回给财务重新审核。"
            else:
                #如果账务未审核
                return super().resultSet(201, "财务还未审核通过,您无法驳回。", [])
        return super().resultSet(200, message, [])
        raise Exception("驳回失败。")
         
    @db.atomic()                   
    def update(self, params):
        """
        审核通过
        """
        print(params)
        transForm = TransForm.get(TransForm.id==params["id"])
        # 判断审核人，写入审核状态
#         if int(params["userid"]) == params["handoverid"]:
#             # 交接人
#             #transForm.handoverstatus=AUDIT_STATUS_PASSED
#             pass
        if int(params["userid"]) == params["supervisorid"] and transForm.supervisorstatus == AUDIT_STATUS_WAITE:
            # 主管 1
            transForm.supervisorstatus=AUDIT_STATUS_PASSED
        elif int(params["userid"]) == params["financeid"] and transForm.financestatus == AUDIT_STATUS_WAITE:
            # 财务 2
            if transForm.supervisorstatus==AUDIT_STATUS_PASSED:
                #如果主管已审核
                transForm.financestatus=AUDIT_STATUS_PASSED
            else:
                #如果主管未审核
                return super().resultSet(201, "主管还未审核通过,您无法操作。", [])
        elif int(params["userid"]) == params["receiverid"] and transForm.receiverstatus == AUDIT_STATUS_WAITE:
            # 接收人4
            if transForm.financestatus==AUDIT_STATUS_PASSED:
                #如果账务已审核
                transForm.receiverstatus=AUDIT_STATUS_PASSED
            else:
                #如果账务未审核
                return super().resultSet(201, "账务还未审核通过,您无法操作。", [])
        if transForm.receiverstatus == AUDIT_STATUS_PASSED \
            and transForm.supervisorstatus == AUDIT_STATUS_PASSED \
            and transForm.financestatus == AUDIT_STATUS_PASSED:
            # 如果是尾款流转，状态设为已流转，如果不是设为已审核
            if transForm.formtype == TRANSFORM_TYPE_ENDED:
                transForm.status = MYCUSTOMER_STATUS_TRANSED
            else:
                # 如果成本，接收人，主管,账务都审核通过，状态改为已审核
                transForm.status= AUDIT_STATUS_PASSED

#             '''主要逻辑实现'''
#             templatefile = TEMPLATE_PATH + "/" + TEMPLATE_XLSX + "/" + TEMPLATE_TRANSFORM_XLSX
#             savefile = DOWNLOAD_PATH + "/" + DOWNLOAD_PATH_TRANSFORM + "/" + DOWNLOAD_PATH_TRANSFORM_XLSX.format(id=params["id"])
#             #先打开已存在的表
#             wb = load_workbook(templatefile)
#             ws = wb["Sheet1"]
#             ws['B3'] = params["sellername"]
#             ws['D3'] = params["outformername"]
#             ws['F3'] = params["src"]
#             ws['G3'] = "收款日期 " + params["collectiondate"]
#             ws['G4'] = "流转日期 " + params["transdate"]
#             ws['B5'] = params["compname"]
#             ws['B6'] = params["contacter"]
#             ws['F5'] = params["legalperson"]
#             ws['B7'] = params["area"]
#             ws['F7'] = params["addresstype"]
#             ws['B8'] = params["business"]
#             ws['B13'] = params["invoicingtype"]
#             ws['F13'] = params["amountinvoicing"]
#             ws['B14'] = params["taxtype"]
#             ws['F14'] = params["servicedateb"] + " - " + params["servicedatee"]
#             ws['B15'] = params["gifts"]
#             ws['D17'] = params["costreg"]
#             ws['F17'] = params["amountreg"]
#             ws['D18'] = params["costaddress"]
#             ws['F18'] = params["amountaddress"]
#             ws['D19'] = params["costchange"]
#             ws['F19'] = params["amountchange"]
#             ws['D20'] = params["costagent"]
#             ws['F20'] = params["amountagent"]
#             ws['D21'] = params["costcrow"]
#             ws['F21'] = params["amountescrow"]
#             ws['D22'] = params["costlogout"]
#             ws['F22'] = params["amountlogout"]
#             ws['D23'] = params["costsocial"]
#             ws['F23'] = params["amountsocial"]
#             ws['D24'] = params["costtail"]
#             ws['F24'] = params["amounttail"]
#             ws['B25'] = "其他（" + params["othername"] + "）"
#             ws['D25'] = params["costother"]
#             ws['F25'] = params["amountother"]
#             ws['F26'] = params["amounttotal"]
#             ws['B27'] = params["amountreceivables"]
#             ws['E27'] = params["amountpayin"]
#             ws['G27'] = params["amountend"]
#             ws['B29'] = params["amountendcondition"]
#             ws['B28'] = params["paytype"]
#             #ws['E28'] = params["financename"]
#             ws['B30'] = str(params["materials"])
#             ws['B38'] = params["memo"]
#             
#             wb.save(savefile)

        transForm.save()
        return super().resultSet(200, "审核通过", [])
        raise Exception("审核失败")
    @db.atomic()
    def add(self, params):
        """
        添加
        """
        print(params)
        transform = TransForm.create(
               mycustomer_id=params["mycustomerid"],
               customer_id=params["customerid"],
               seller_id=params["sellerid"],
               outformer_id=params["outformerid"],
               src=params["src"],
               signtype=params["signtype"],
               collectiondate=params["collectiondate"],
               transdate=params["transdate"],
               addresstype=params["addresstype"],
               paytype=params["paytype"],
               business=params["business"],
               invoicingtype=params["invoicingtype"],
               amountinvoicing=params["amountinvoicing"],
               gifts=params["gifts"],
               amounttotal=params["amounttotal"],
               amountreceivables=params["amountreceivables"],
               amountpayin=params["amountpayin"],
               amountend=params["amountend"],
               amountendcondition=params["amountendcondition"],
               finance_id=params["financeid"],
               financestatus=AUDIT_STATUS_WAITE,
               materials=json.dumps(params["materials"]),
               handover_id=params["handoverid"],
               handoverstatus=AUDIT_STATUS_WAITE,
               receiver_id=params["receiverid"],
               receiverstatus=AUDIT_STATUS_WAITE,
               supervisor_id=params["supervisorid"],
               supervisorstatus=AUDIT_STATUS_WAITE,
               status=AUDIT_STATUS_WAITE,
               formtype = TRANSFORM_TYPE_NORMAL,
               annex=json.dumps(params["annex"]),
               memo=params["memo"],
               discount_id=params["discount_id"]
        )
        for item in params["service"]:
            TransFormDetail.create(
                transform= transform.id,
                servicedetail_id = item["id"],
                service_id = item["serviceid"],
                unit=item["unit"],
                amount=item["amount"],
                totalprice=item["totalprice"],
                cost=item["cost"],
                price=item["price"],
                memo=item["memo"]
            )

        for rec in params["recorder"]:
            annex = []
            for item in rec["annex"]:
                annex.append(item['name'])

            TransFormRecorder.create(
                transform= transform.id,
                collectiondate = rec["collectiondate"],
                reciver_id = rec["reciverid"],
                totalprice = rec["totalprice"],
                loantype=rec["loantype"],
                memo=rec["memo"],
                annex= json.dumps(annex)
            )
        '''更新我的客户状态为已流转'''
        whereis = (MyCustomer.id == params["mycustomerid"])
        MyCustomer.update(
            {MyCustomer.status: MYCUSTOMER_STATUS_TRANSED}
        ).where(whereis).execute()
        '''更新公共客户字段税务类型'''
        whereis = (Customer.id == params["customerid"])
        Customer.update(
            {Customer.taxtype: params["taxtype"]}
        ).where(whereis).execute()
        
        # 创建统计数据
        view = MyCustomerView()
        view.createSummaryData(params["sellerid"])
        # 取得当前日期的跟踪数据
        curdaycondtion = (SummaryTrack.tracker == params["sellerid"]) & (SummaryTrack.date == time.strftime("%Y-%m-%d", time.localtime()))
        strack = SummaryTrack.get(curdaycondtion)
        # 流转数量加1
        strack.moveto =strack.moveto +1
        strack.save()
        
        return super().resultSet(200, "流转成功", [])
        raise Exception("流转失败")
    

    def getLast(self, id):
        """根据ID取得最后流转单，params：条件参数"""
        row = TransForm.select().where(TransForm.mycustomer_id == id).order_by(TransForm.transdate.desc()).first()
        if row:
            service = []
            recorder =  []
            # 服务明细
            trows = TransFormDetail.select().where(TransFormDetail.transform == row.id)
            for trow in trows:
                try:
                    service.append({"id":trow.servicedetail_id, "transformid":trow.transform_id, "spec":trow.servicedetail.spec, "type":trow.servicedetail.type,  \
                                    "name":trow.service.name, "serviceid":trow.service_id, "items":trow.servicedetail.items, "amount":trow.amount, "totalprice":trow.totalprice, "unit":trow.unit, \
                                    "cost":trow.cost, "price":trow.price, "memo":trow.memo})
                except:
                    continue
            # 收款 记录
            rrows = TransFormRecorder.select().where(TransFormRecorder.transform == row.id)
            for rrow in rrows:
                annexs=[]
                for annex in json.loads(rrow.annex):
                    annexs.append({"name":annex,"url":API_TRANSFORMRECORDER_ANNEX_DOWNLOAD +str(row.mycustomer_id) + "/" + annex})
                recorder.append({"id":rrow.id, "transformid":rrow.transform_id, "collectiondate":str(rrow.collectiondate), \
                                 "loantype":rrow.loantype, "totalprice":rrow.totalprice, "annex":annexs, "reciverid":rrow.reciver_id, \
                                 "memo":rrow.memo})

            annexs = []
            for annex in json.loads(row.annex):
                annexs.append(
                    {"name": annex, "url": API_TRANSFORM_ANNEX_DOWNLOAD + annex})
            newprice=0
            oldprice=0
            preferential_description=""
            if row.discount_id != 0:
                newprice=row.discount.new_price
                oldprice=row.discount.price
                preferential_description=row.discount.preferential_description
            data = {
                "id":row.id,
                "sellerid":row.seller.id,
                "sellername":row.seller.username,
                "outformerid":row.outformer.id,
                "outformername":row.outformer.username,
                "src":row.src,
                "signtype":row.signtype,
                "service":service,
                "recorder":recorder,
                "collectiondate":str(row.collectiondate),
                "transdate":str(row.transdate),
                "compname":row.customer.compname,
                "legalperson":row.customer.legalperson,
                "contacter":row.customer.contacter,
                "area":row.customer.area,
               "address":row.customer.address,
               "phone":row.customer.phone,
               "addresstype":row.addresstype,
               "business":row.business,
               "invoicingtype":row.invoicingtype,
               "amountinvoicing":row.amountinvoicing,
               "taxtype":row.customer.taxtype,
               "gifts":row.gifts,
               "amounttotal":row.amounttotal,
               "amountreceivables":row.amountreceivables,
               "amountpayin":row.amountpayin,
               "amountend":row.amountend,
               "paytype":row.paytype,
               "payimg":row.payimg,
               "amountendcondition":row.amountendcondition,
               "financeid":row.finance.id,
               "financename":row.finance.username,
               "financestatus":row.financestatus,
               "materials":json.loads(row.materials),
               "handoverid":row.handover.id,
               "handovername":row.handover.username,
               "handoverstatus":row.handoverstatus,
               "receiverid":row.receiver.id,
               "receivername":row.receiver.username,
               "receiverstatus":row.receiverstatus,
               "supervisorid":row.supervisor.id,
               "supervisorname":row.supervisor.username,
               "supervisorstatus":row.supervisorstatus,
               "mycustomerid":row.mycustomer.id,
               "customerid":row.customer.id,
               "status":row.status,
               "annex":annexs,
               "memo":row.memo,
               "discount_id":row.discount_id,
               "preferentialdescription":preferential_description,
               "newprice":newprice,
               "oldprice":oldprice
            }
            return super().resultSet(200, "", data)
        else:
            return super().resultSet(201, "", {})

    def checkFirstForm(self, applicant_id):
        """检查是否是新人第一个优惠单"""
        count = TransForm.select().where((TransForm.seller_id == applicant_id)\
                                            & (TransForm.status != AUDIT_STATUS_OVER)\
                                            & (TransForm.status != AUDIT_STATUS_CANCLE)).count()
        return super().resultSet(200, "",[],total=count)
